import { createVNode, render } from "../../assets/vue3/vue.esm-browser.js";

let top = 20;
let noticeItems = [];

const createVueMsg = function (msg, info, icon, top) {
    // createVNode 和 createApp 一样用于构建vue实例对象,所以参数相同
    //      createApp 构建的应用必须通过挂载方式才能完成实例创建
    //      createVNode 可以跳过挂载直接生成虚拟DOM
    return createVNode({
        template: `
        <div class="msg-box in" :style=" { top:top+'px' } ">
            <div class="icon" v-if=" icon!='' ">
                <i class="iconfont" :class=" icons[icon] "></i>
            </div>
            <div class="desc">
                <p class="title">{{ msg }}</p>
                <p v-if="info!=''">{{ info }}</p>
            </div>
            <div class="btn">
                <i class="iconfont icon-close2"></i>
            </div>
        </div>
        `,
        data() {
            return {
                msg: msg,
                info,
                icons: {
                    success: "icon-success1",
                    info: "icon-info",
                    warning: "icon-warning",
                    error: "icon-error",
                    question: "icon-question"
                },
                icon,
                top
            }
        },
    })
}

const showTip1 = function (msg = "消息", info = "", icon = "") {
    let vnode = createVueMsg(msg, info, icon)
    console.log(vnode)
    console.log(vnode.el) // el 是当前虚拟DOM 渲染后对应 真实DOM
    // 基于vue的渲染函数，将虚拟DOM节点进行解析，并完成vue模板语法关联，以及真实DOM创建生成
    // 创建的DOM对象必须提供一个临时容器进行存储记录
    let box = document.createDocumentFragment();
    render(vnode, box);
    console.log(vnode.el);
    document.body.appendChild(vnode.el)
}

const showTip = function (msg = "消息", info = "", icon = "") {
    let vnode = createVueMsg(msg, info, icon, top)
    let box = document.createDocumentFragment();
    render(vnode, box);

    vnode.el.addEventListener("animationend",(event)=>{
        if(event.animationName == "moveOut"){
            document.body.removeChild(vnode.el)
        }
    })

    let key = Math.random(); 
    noticeItems[key] = vnode.el;

    document.body.appendChild(vnode.el)

    let domH = vnode.el.clientHeight+20;
    // 记录下次提示DOM出现的位置
    top += domH;
    setTimeout(()=>{
        vnode.el.className = "msg-box out";
        top -= domH;
        // 记录当前元素位置用于后续判断，防止手动删除时，元素位置计算错误
        let currentDomTop = parseFloat(vnode.el.style.top)
        // 删除记录中的当前元素
        delete noticeItems[key];
        // 修正页面现存元素的新位置
        for (let k in noticeItems) {
            let tempTop = parseFloat(noticeItems[k].style.top);
            // 位置小于当前元素高度时 不需要 进行位置更新
            if(tempTop>currentDomTop){
                tempTop -= domH;
                noticeItems[k].style.top = tempTop +"px";
            }
        }
    }, 5000);
}

export default showTip;